package com.fyzk.activity.lottery.shuzicai;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.LinearLayout;

import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.myview.WeiZhi;
import com.tyjc.lottery.R;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 选球View
 *
 * @author miao
 */
public class SelectBallView extends LinearLayout {

    private Context context;

	/* 屏幕中一行最多显示的球的个数（用来计算球的边长） */
//	private static final int h_max_count = 8;
    /**
     * 球的直径
     */
    private int ball_diameter;
    /**
     * 屏幕中一行需要显示的球的个数
     */
    private int h_show_count = 8;
    /* // 行之间的间距 */
    private int h_jianJu = 15;
    private boolean isJianJu;

    private Bitmap bitmap_ballsel;
    /* 小球未选中状态的图片 */
    private Bitmap bitmap_ballnormal;
    /* 选中状态下小球的字体颜色 */
    private int color_balltxt_sel;
    /* 未选中状态下小球的字体颜色 */
    private int color_balltxt_nor = 0xff333333;

    /**
     * 球区与屏幕两边的间距
     */
    private int screen_margin = 20;
    /**
     * 球间距
     */
    private int ballMargin = 6;

    private Paint paint_ball;
    private Paint paint_txt;

    private int screen_width, screen_height, screen_DPI;
    private float screen_density;

    private boolean isXuanQiu = false;

    private List<BallInfo> list_qiu = new ArrayList<BallInfo>();
    private List<Integer> missValues = new ArrayList<>();
    private int maxMissValue = 0;

    /* 选球数  */
    private int select_count;
    /* 最大选球数  */
    private int select_max = 100;

    /**
     * 小球总个数
     */
    private int count;

    private String TAG = "SelectBallView";
    /**
     * 球类型 —— 红、蓝
     */
    private int ballType = 0;
    /* 关联选球控件*/
//	private SelectBallView guanLian_view;
    private List<SelectBallView> guanLian_views = new ArrayList<SelectBallView>();

    /**
     * 遗漏值高度
     */
    private int missHeight = 0;
    /* 正常情况下遗漏值的颜色 */
    public int color_miss_nor;
    private boolean isShowMiss = true;

    public void setShowMiss(boolean showMiss) {
        isShowMiss = showMiss;
    }

    public SelectBallView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        this.context = context;
        init();
        initAttrValue(attrs);
    }

    public SelectBallView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        this.context = context;
        init();
        initAttrValue(attrs);
    }

    public SelectBallView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.context = context;
        init();
    }

    private void initAttrValue(AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.SelectBallView);
        int N = typedArray.getIndexCount();
        int resourceId;
//        bitMapRecycle(bitmap_ballnormal);
//        bitMapRecycle(bitmap_ballsel);
        for (int i = 0; i < N; i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.SelectBallView_ball_nor:
                    resourceId = typedArray.getResourceId(
                            R.styleable.SelectBallView_ball_nor, 0);
                    bitmap_ballnormal = BitmapFactory.decodeResource(
                            context.getResources(), resourceId);
                    break;
                case R.styleable.SelectBallView_ball_sel:
                    resourceId = typedArray.getResourceId(
                            R.styleable.SelectBallView_ball_sel, 0);
                    bitmap_ballsel = BitmapFactory.decodeResource(
                            context.getResources(), resourceId);
                    break;
                case R.styleable.SelectBallView_lineNums:
                    resourceId = typedArray.getInt(
                            R.styleable.SelectBallView_lineNums, 8);
                    h_show_count = resourceId;
                    break;
                case R.styleable.SelectBallView_txtcolor_nor:
                    resourceId = typedArray.getColor(
                            R.styleable.SelectBallView_txtcolor_nor, 0x0);
                    color_balltxt_nor = resourceId;
                    break;
                case R.styleable.SelectBallView_txtcolor_sel:
                    resourceId = typedArray.getColor(
                            R.styleable.SelectBallView_txtcolor_sel, 0x0);
                    color_balltxt_sel = resourceId;
                    break;
                case R.styleable.SelectBallView_ballType:
                    resourceId = typedArray.getInt(
                            R.styleable.SelectBallView_ballType, 0x0);
                    ballType = resourceId;
                    break;
                case R.styleable.SelectBallView_jianJu:
                    isJianJu = typedArray.getBoolean(R.styleable.SelectBallView_jianJu, false);
                    break;
                case R.styleable.SelectBallView_isShowMiss:
                    isShowMiss = typedArray.getBoolean(R.styleable.SelectBallView_isShowMiss, true);
                    break;
//			case R.styleable.SelectBallView_margin:
//				resourceId = typedArray.getInt(
//						R.styleable.SelectBallView_margin, 6);
//				screen_margin = resourceId;
//				break;
            }
        }
        color_miss_nor = Color.BLACK;
        if (isJianJu) {
            screen_margin = screen_width / h_show_count / 4;
            ball_diameter = (screen_width - screen_margin * 2) / h_show_count;
            ballMargin = ball_diameter / 16;
        } else {
            ball_diameter = (screen_width - screen_margin * 2) / h_show_count;
        }
        if (isShowMiss) {
            missHeight = screen_width/16;
        } else {
            missHeight = 0;
        }
        invalidate();
    }

    private void init() {
        setWillNotDraw(false);
        if (isInEditMode()) {
            return;
        }
        // TODO Auto-generated method stub
        this.screen_width = ScreenUtils.getInstance().getWidth();
        this.screen_height = ScreenUtils.getInstance().getHeight();
        this.screen_DPI = ScreenUtils.getInstance().getDensityDPI();
        this.screen_density = ScreenUtils.getInstance().getDensity();
        ball_diameter = (screen_width - screen_margin * 2) / h_show_count;

        setFocusable(true);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (paint_ball == null) {
            paint_ball = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint_ball.setColor(Color.BLACK);
            paint_ball.setAntiAlias(true);
            paint_ball.setTextSize(20 * screen_density);
            paint_ball.setTextAlign(Align.CENTER);
        }

        if (paint_txt == null) {
            paint_txt = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint_txt.setAntiAlias(true);

            paint_txt.setTextAlign(Align.CENTER);
            Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
            paint_txt.setTypeface(font);
        }

        for (int i = 0; i < count; i++) {
            int left = 0;
            int right = 0;
            int top = 0;
            int bottom = 0;
            if (isJianJu) {
                left = (i % h_show_count) * ball_diameter + screen_margin;
                right = left + ball_diameter;
                top = (ball_diameter + missHeight) * (i / h_show_count);
                bottom = top + ball_diameter * 3 / 4;
            } else {
                left = (i % h_show_count) * ball_diameter + screen_margin;
                right = left + ball_diameter;
                top = (ball_diameter + missHeight) * (i / h_show_count) + h_jianJu
                        * (i / h_show_count + 1);
                bottom = top + ball_diameter;
            }
            paint_txt.setTextSize(Math.round(ball_diameter/3));
            // 画球
            Rect rect = new Rect(left + ballMargin, top + ballMargin, right - ballMargin, bottom
                    - ballMargin);
            list_qiu.get(i).rect_left = left;
            list_qiu.get(i).rect_top = top;
            list_qiu.get(i).rect_right = right;
            list_qiu.get(i).rect_bottom = bottom;

            if (list_qiu.get(i).isSelected()) {
                paint_txt.setColor(color_balltxt_sel);
                canvas.drawBitmap(bitmap_ballsel, null, rect, paint_ball);
            } else {
                paint_txt.setColor(color_balltxt_nor);
                canvas.drawBitmap(bitmap_ballnormal, null, rect, paint_ball);
            }
            drawText(canvas, paint_txt, list_qiu.get(i), rect);


            if (isShowMiss) {
                // 遗漏
                Paint paintMiss = new Paint(Paint.ANTI_ALIAS_FLAG);
                paintMiss.setAntiAlias(true);
                paintMiss.setTextSize(12 * screen_density);
                paintMiss.setTextAlign(Align.CENTER);
                Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
                paintMiss.setTypeface(font);
                Rect missRect = new Rect(rect.left, rect.bottom, rect.right, rect.bottom + missHeight);
                String missValue = "--";
                if (missValues.size() == count) {
                    missValue = missValues.get(i)+"";
                    if (missValues.get(i) >= maxMissValue) {
                        paintMiss.setColor(Color.RED);
                    } else {
                        paintMiss.setColor(color_miss_nor);
                    }
                }

                drawText(canvas, paintMiss, missValue, missRect);
            }


        }
    }

    /**
     * 触屏事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        long startTime = System.currentTimeMillis();
        select_count = getSelectedCount();
        int x, y;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = (int) event.getX();
                y = (int) event.getY();
                for (int i = 0; i < list_qiu.size(); i++) {
                    Rect r = new Rect(list_qiu.get(i).rect_left, list_qiu.get(i).rect_top,
							list_qiu.get(i).rect_right
                            , list_qiu.get(i).rect_bottom);
                    if (r.contains(x, y)) {
                        isXuanQiu = true;
                        WeiZhi w = new WeiZhi(r.left, r.right, r.top, r.bottom, x,
                                y, list_qiu.get(i).getNum());
                        w.setType(ballType);
                        w.isShowMoveBall = true;
                        TouZhuHelper.getInstance().ballClick(w);
                        break;
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                // int what = WHAT_UP;
                x = (int) event.getX();
                y = (int) event.getY();
                if (isXuanQiu) {
                    for (int i = 0; i < list_qiu.size(); i++) {
                        BallInfo info = list_qiu.get(i);
                        Rect r = new Rect(info.rect_left, info.rect_top, info.rect_right
                                , info.rect_bottom);
                        if (r.contains(x, y)) {

                            if (info.isSelected()) {
                                select_count--;
                                info.setSelected(false);
                            } else {
                                select_count++;
                                if (select_count > select_max) {
                                    select_count--;
                                    AppToast.getToast().show("最多可选" + select_max + "个球");
                                } else {
                                    for (SelectBallView guanLian_view : guanLian_views) {

                                        if (i < guanLian_view.getBallInfoList().size()) {
                                            BallInfo info1 = guanLian_view.getBallInfoList().get(i);
                                            if (guanLian_view != null && info1.isSelected()) {
                                                info1.setSelected
                                                        (false);
                                                guanLian_view.setSelect_count(guanLian_view
                                                        .getSelect_count() - 1);
                                                guanLian_view.invalidate();
                                            }
                                        }
                                    }
                                    info.setSelected(true);
                                }
                            }
                        }
                    }
                }
                isXuanQiu = false;
                WeiZhi w = new WeiZhi();
                w.isShowMoveBall = false;

                TouZhuHelper.getInstance().ballClick();
                TouZhuHelper.getInstance().ballClick(w);
                this.invalidate();
                // WeiZhi w = new WeiZhi();
                // sendMessage(what, w);
                break;
        }
        long endTime = System.currentTimeMillis();
        LogUtil.d("time: "+(endTime-startTime)*1.0/1000);
        return true;
    }

    public void setBallInfoList(List<BallInfo> list_qiu) {
        this.list_qiu = list_qiu;
        count = this.list_qiu.size();
        select_count = 0;
        for (int i = 0; i < list_qiu.size(); i++) {
            if (list_qiu.get(i).isSelected()) {
                select_count++;
            }
            list_qiu.get(i).type = ballType;
        }
        invalidate();// 更新界面
    }

    public void setBallInfoList(List<BallInfo> list_qiu, int count) {
        this.list_qiu = list_qiu;
        this.count = count;
        select_count = 0;
        for (int i = 0; i < list_qiu.size(); i++) {
            if (list_qiu.get(i).isSelected()) {
                select_count++;
            }
            list_qiu.get(i).type = ballType;
        }
        invalidate();// 更新界面
    }

    private int getSelectedCount() {
        int sel = 0;

        for (BallInfo info : this.list_qiu) {
            if (info.isSelected()) {
                sel++;
            }
        }
        return sel;
    }


    public List<BallInfo> getBallInfoList() {
        return this.list_qiu;
    }

    @Override
    public void invalidate() {
        // TODO Auto-generated method stub
        super.invalidate();
    }

    /**
     * 绘制文字
     *
     * @param canvas
     * @param paint
     * @param info
     * @param rect
     */
    private void drawText(Canvas canvas, Paint paint, BallInfo info, Rect rect) {
        String text = info.getNum();
        FontMetrics fm = paint.getFontMetrics();
        int baseLine = (int) (rect.top
                + (rect.bottom - rect.top - fm.bottom + fm.top) / 2 - fm.top);

        if (info.prize != null && !info.prize.equals("")) {
            canvas.drawText(text, rect.centerX(), baseLine - (fm.bottom - fm.top) / 3, paint);
            paint.setTextSize(12 * screen_density);
            Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
            paint.setTypeface(font);
            String prizeStr = "" + info.prize;
            canvas.drawText(prizeStr, rect.centerX(), baseLine + (fm.bottom - fm.top) / 3, paint);
        } else {
            canvas.drawText(text, rect.centerX(), baseLine, paint);
        }
    }

    /**
     * 绘制文字
     *
     * @param canvas
     * @param paint
     * @param text
     * @param rect
     */
    private void drawText(Canvas canvas, Paint paint, String text, Rect rect) {
        FontMetrics fm = paint.getFontMetrics();
        int baseLine = (int) (rect.top
                + (rect.bottom - rect.top - fm.bottom + fm.top) / 2 - fm.top);

        canvas.drawText(text, rect.centerX(), baseLine, paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = this.screen_width;
        int height = (count / h_show_count) * (ball_diameter + h_jianJu + missHeight);
        if (count % h_show_count != 0) {
            height = (count / h_show_count + 1) * (ball_diameter + h_jianJu + missHeight);
        }
        setMeasuredDimension(width, height);
    }

    public int getSelect_max() {
        return select_max;
    }

    public void setSelect_max(int select_max) {
        this.select_max = select_max;
    }


    public void setGuanLian_view(SelectBallView guanLian_view) {
        this.guanLian_views.clear();
        this.guanLian_views.add(guanLian_view);
    }

    public void setGuanLian_view(List<SelectBallView> guanLian_views) {
        this.guanLian_views.clear();
        this.guanLian_views.addAll(guanLian_views);
    }

    public int getSelect_count() {
        return select_count;
    }

    public void setSelect_count(int select_count) {
        this.select_count = select_count;
    }

    public void setMissValues(List<Integer> missValues) {
        this.missValues = missValues;
        maxMissValue = 0;
        for (int i =0; i < missValues.size(); i++) {
            if (maxMissValue < missValues.get(i)) {
                maxMissValue = missValues.get(i);
            }
        }
        invalidate();
    }

    private void bitMapRecycle(Bitmap bitmap) {
        if(bitmap != null && !bitmap.isRecycled()){
            bitmap.recycle();
            bitmap = null;
        }
    }

    public void recycleBitmap() {
        bitMapRecycle(bitmap_ballnormal);
        bitMapRecycle(bitmap_ballsel);
    }
}
